<?php 
namespace Home\Model;
use Think\Model;
class PrizeModel extends Model 
{
    public function getPrize()
    {
        $list = $this->getPrizeList();
        if(empty($list)){
            $prize = array(
                'id'=>0
            );
            return $prize;
        }
        $prizeCount = count($list);
        $prizeId = rand(0,$prizeCount-1);
        $prize = $list[$prizeId];
        $where = array(
            'id'     => $prize['id'],
            'lucknum'=> array('LT', $prize['num']),
        );
        $result = $this->where($where)->setInc('lucknum');
        if($result===0){
            S('PrizeList',null);
            $prize = array(
                'id'=>0
            );
        }
        return $prize;
    }
    /**
     * 根据id获取一个奖品的名字
     */
    public function getIdPrizeName($id)
    {
        $name = S('PrizeModel_getIdPrizeName_'.$id);
        if(!empty($name))
            return $name;
        $where = array(
            'id'     => $id,
        );
        $result = $this->field('name')->where($where)->find();
        $name = $result['name'];
        S('PrizeModel_getIdPrizeName_'.$id, $name, array('expire'=>3600));
        return $name;
    }
    /**
     * 获取一个可选奖品的列表
     */
    private function getPrizeList()
    {
        $list = S('PrizeList');
        if($list)
            return $list;
        $where = "num > lucknum";
        $field = array(
            'id',
            'name',
            'num'
        );
        $list = $this->where($where)->field($field)->select();
        S('PrizeList', $list, array('expire'=>30));
        return $list;
    }
}
